package com.jieao.framework.interceptor.impl;

import com.jieao.biz.domain.SiteIntercept;
import com.jieao.common.constant.Constants;
import com.jieao.common.utils.CacheUtils;
import com.jieao.common.utils.StringUtils;
import com.jieao.framework.util.ShiroUtils;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Description 前端拦截器
 * @Author weifanl
 * @Date2020/9/1 11:52
 **/
@Component
public class FrontInterceptor extends HandlerInterceptorAdapter {
    //拦截类型 登录
    private static String INTER_TYPE = "login";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object cacheObj = CacheUtils.get(Constants.FRONT_INTER_CACHE, Constants.FRONT_INTER_KEY);
        List<SiteIntercept> siteIntercepts = StringUtils.cast(cacheObj);
        String requestURI = request.getRequestURI();
        requestURI = requestURI.replace("/front", "");

        for (SiteIntercept siteIntercept : siteIntercepts) {
            if (StringUtils.isEmpty(siteIntercept.getUrl())) {
                continue;
            }
            //过滤掉没拦截到的url
            String url = siteIntercept.getUrl().replace("/front", "");
            if (url.indexOf("*") == -1 && !url.equals(requestURI)) {
                continue;
            }
            url = url.replace("*", "");
            if (url.indexOf("*") != -1 && requestURI.indexOf(url) == -1) {
                continue;
            }

            //拦截前端登录
            if (INTER_TYPE.equals(siteIntercept.getType()) && null == ShiroUtils.getUserId()) {
                //设置跳转地址
                response.setHeader("redirectUrl", siteIntercept.getRedirectUrl());
                //设置跳转使能
                response.setHeader("enableRedirect", "true");
                return false;
            }
        }
        return true;
    }
}
